package com.stu.spring04.aspect;

import com.stu.spring04.annotation.UserAnnotation;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Date;

/**
 * ClassName: AddressAspect
 * Package: com.stu.spring04.aspect
 * Description: @Version 1.0
 */
@Aspect
@Component
public class AddressAspect {
    @Pointcut("execution(public * com.stu.spring04.service.impl.AddressServiceImpl.add*(..))")
    public void myMethod(){
        //假设这个方法就是被代理的方法
    }
    @Before("myMethod()")
    //JoinPoint 链接点
    public void beforeMethod(JoinPoint joinPoint) throws IllegalAccessException {
        System.out.println("开始新增地址，拦截");
        for (Object eve:joinPoint.getArgs()) {
            Class<?> aClass = eve.getClass();
            Field[] declaredFields = aClass.getDeclaredFields();
            for (Field every:declaredFields ) {
                if (every.getName().equals("createBy")){
                    every.setAccessible(true); //暴力破解私有
                    every.set(eve,"健辉");
                }
                if (every.getName().equals("createTime")){
                    every.setAccessible(true); //暴力破解私有
                    every.set(eve,new Date());
                }
                UserAnnotation annotation = every.getAnnotation(UserAnnotation.class);
                if(annotation!=null&&annotation.status()==false){
                    every.setAccessible(true);
                    every.set(eve,null);
                }
            }
        }

    }
    //后置
    @After("myMethod()")
    public void afterMethod(){
        System.out.println("新增成功，放走");
    }
}
